﻿using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;

public static class UserConnectionService
{
    // 显式初始化 ConcurrentDictionary
    private static readonly ConcurrentDictionary<string, HashSet<string>> _userConnections =
        new ConcurrentDictionary<string, HashSet<string>>();

    public static IEnumerable<string> GetAllUsers()
    {
        // 返回当前所有用户编号的快照（线程安全）
        return _userConnections.Keys.ToList(); 
    }

    public static void AddConnection(string userId, string connectionId)
    {
        _userConnections.AddOrUpdate(
            userId,
            key => new HashSet<string> { connectionId }, // 当 key 不存在时，创建新集合
            (key, existingSet) =>
            {
                existingSet.Add(connectionId);
                return existingSet;
            }
        );
    }

    public static void RemoveConnection(string userId, string connectionId)
    {
        if (!_userConnections.TryGetValue(userId, out var connections))
            return;

        lock (connections) // 确保线程安全
        {
            connections.Remove(connectionId);
            if (connections.Count == 0)
            {
                _userConnections.TryRemove(userId, out _);
            }
        }
    }

    public static IEnumerable<string> GetConnectionIds(string userId)
    {
        return _userConnections.TryGetValue(userId, out var connections)
            ? connections
            : Enumerable.Empty<string>();
    }
}